home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 3734 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.0 KB

  1. Path: hubcap.clemson.edu!hubcap!mjs
  2. From: mjs@hubcap.clemson.edu (M. J. Saltzman)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: division problem
  5. Date: 30 Jan 96 21:03:17 GMT
  6. Organization: Clemson University
  7. Message-ID: <mjs.823035797@hubcap>
  8. References: <31097D77.11AA@rain.org> <26JAN199622082450@erich.triumf.ca> <4eh246$u6h@airdmhor.gen.nz> <4ej4ha$66@fountain.mindlink.net> <DLzvGG.2rn@uns.bris.ac.uk>  <Pine.SOL.3.90.960130150923.21923F-100000@flute>
  9. NNTP-Posting-Host: hubcap.clemson.edu
  10.  
  11. Darrell Grainger <a378grai@cdf.toronto.edu> writes:
  12.  
  13. |On Tue, 30 Jan 1996, Nathan Sidwell wrote:
  14.  
  15. |> : >celcius = (fahrenheit - 32) * 5 / 9;
  16. |> 
  17. |> :      That's disgusting <g> as it doesn't round.  Try it with 39 deg F:
  18. |> :           (39-32)*5/9 ::= 7*5/9 ::= 35/9 ::= 3
  19. |> : but the actual value is 3.8... i.e. nearly 4.  If you must int, 4
  20. |> : would be a better answer.
  21. |> 
  22. |> Still no need to use floating point,
  23. |> celcius = ((fahrenheit - 32) * 5 + 4) / 9
  24.  
  25. |This ALMOST does the trick but 4/9 = 0.44444444... and 5/9 = 0.555555....
  26. |What you really want to do to eliminate the rounding errors is add 0.5 to
  27. |the number, e.g. 1.49999... + 0.5 = 1.9999... and (int)1.9999... = 1. So
  28. |1.49999... rounds down to 1. Then 1.5 + 0.5 = 2.0 and (int)2.0 = 2. So
  29. |1.5 rounds up to 2. This is what most people consider correct rounding.
  30.  
  31. For arbitrary floating-point results, this is correct, but...
  32.  
  33. |In your 'trick' you would have 1.5 + 0.4444... = 1.9444... and
  34. |(int)1.9444... = 1. This means that 1.5 rounds down to 1. This is not
  35. |proper. It is close but not proper. Alternatively, adding 5/9th would round
  36. |up certain numbers it should not.
  37.  
  38. ...in this particular example, we know that the result of the division
  39. will have a fractional part equal to n/9, 0 <= n <= 8.  In this case, 
  40. we see that adding 4/9 to a fractional part <= 4/9 and truncating 
  41. rounds down, but adding 4/9 to a fractional part >= 5/9 and truncating
  42. rounds up.  Quite clever, actually.
  43. -- 
  44.         Matthew Saltzman
  45.         Clemson University Math Sciences
  46.         mjs@clemson.edu
  47.